package by.gamedev.site.client.app.place;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.requestfactory.shared.EntityProxy;
import com.google.gwt.requestfactory.shared.EntityProxyId;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.requestfactory.shared.RequestFactory;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

/**
 * Extends {@link AbstractProxyEditActivity} to work from a {@link EntityProxyId}
 * 
 * @param <P>
 *            the type of proxy to find and edit
 */
public abstract class FindAndEditProxy<P extends EntityProxy> extends AbstractProxyEditActivity<P> {

    private final RequestFactory   factory;
    private final EntityProxyId<P> proxyId;
    P                              proxy;

    public FindAndEditProxy(final EntityProxyId<P> proxyId, final RequestFactory factory, final ProxyEditView<P, ?> view,
            final PlaceController placeController) {
        super(view, placeController);
        this.proxyId = proxyId;
        this.factory = factory;
    }

    @Override
    public void start(final AcceptsOneWidget display, final EventBus eventBus) {
        factory.find(proxyId).with(view.createEditorDriver().getPaths()).fire(new Receiver<P>() {
            @SuppressWarnings("synthetic-access")
            @Override
            public void onSuccess(final P response) {
                proxy = response;
                FindAndEditProxy.super.start(display, eventBus);
            }
        });
    }

    @Override
    protected P getProxy() {
        return proxy;
    }
}
